package com.quanwe.common.net

import android.os.Looper
import okhttp3.HttpUrl
import okhttp3.OkHttpClient
import okhttp3.logging.HttpLoggingInterceptor
import org.jetbrains.anko.doAsync
import org.jetbrains.anko.uiThread
import retrofit2.Call
import retrofit2.Retrofit
import retrofit2.converter.gson.GsonConverterFactory

/**
 * 接口管理，用于创建请求实例
 * Created by WQ on 2017/9/20.
 */

object APIManager {
    internal var request: API
    internal var mobApi: MobAPI

    init {
        request = initAPI()
        mobApi = initMobApi()
    }

    private fun initAPI(): API {
        /**
         * 配置OkHtttpClient一些东西
         */
        val client = OkHttpClient.Builder()
                .addInterceptor(addConfigInterceptor())
                .addNetworkInterceptor(
                        HttpLoggingInterceptor().setLevel(HttpLoggingInterceptor.Level.BODY))
                .hostnameVerifier { s, sslSession -> true }
                .build()
        /**
         * 创建请求实例
         */
        val retrofit = Retrofit.Builder()
                .baseUrl("https://manager.quanwe.top/Api/") //设置网络请求的Url地址
                .addConverterFactory(GsonConverterFactory.create()) //设置数据解析器
                .client(client)
                .build()
        // 创建 网络请求接口 的实例
        return retrofit.create(API::class.java)
    }

    private fun initMobApi(): MobAPI {
        /**
         * 配置OkHtttpClient一些东西
         */
        val client = OkHttpClient.Builder()
                .addInterceptor(MobConfigInterceptor())
                .addNetworkInterceptor(
                        HttpLoggingInterceptor().setLevel(HttpLoggingInterceptor.Level.BODY))
                .hostnameVerifier { s, sslSession -> true }
                .build()
        val retrofitMobApi = Retrofit.Builder()
                .baseUrl("http://apicloud.mob.com/") //设置网络请求的Url地址
                .addConverterFactory(GsonConverterFactory.create()) //设置数据解析器
                .client(client)
                .build()
        // 创建 网络请求接口 的实例
        return retrofitMobApi.create(MobAPI::class.java)
    }

    class MobConfigInterceptor : addConfigInterceptor() {
        override fun appendQueryForm(httpUrlBuilder: HttpUrl.Builder) {
            httpUrlBuilder.addQueryParameter("key", MobAPI.KEY)
        }
    }

    class NAction<T : BaseBean<U>, U> {
        constructor(request: Call<T>,block: NAction<T, U>.() -> Unit) {
            block()
            readyCall()
            request.isAsynOK {
                responeCall(this)
                if (success()) {
                    sucCall(status, msg, info)
                    sucCall2(info)
                } else {
                    errCall(status, msg, info)
                }
            }
        }

        lateinit var request: Call<T>
        var responeCall: (BaseBean<U>) -> Unit = {}
        var errCall: (status: Int, msg: String, result: U?) -> Unit = { status, msg, result -> }
        var sucCall: (status: Int, msg: String, result: U?) -> Unit = { status, msg, result -> }
        var sucCall2:(result: U?)->Unit={}
        var readyCall: () -> Unit = {}
        /**
         * 网络请求的成功回调
         */
        fun <T : BaseBean<U>, U> Call<T>.isOK(callback: BaseBean<U>.() -> Unit) {
            val body = execute().body()
            if (body != null && body.success()) {
                callback(body)
            } else {
                callback(BaseBean { msg = "网络请求失败" })
            }
        }


        fun <U> BaseBean<U>.success(): Boolean = this?.status == 1 || this?.status == 200
        /**
         * 网络请求的成功回调
         */
        fun <T : BaseBean<U>, U> Call<T>.isAsynOK(callback: BaseBean<U>.() -> Unit) {
            if (Looper.getMainLooper() == Looper.myLooper()) {
                //不再
                doAsync {
                    val body = execute().body()
                    uiThread {
                        if (body != null && body.success()) {
                            callback(body)
                        } else {
                            callback(BaseBean { msg = "网络请求失败" })
                        }
                    }
                }
            } else {
                isOK(callback)
            }
        }

    }

}
